<template>
  <div id="write" v-title :data-title="title">
    <div class="publish" v-if="this.articleForm.editor.toolbarsFlag">
      <el-button type="primary" @click="publishShow"
        >发布<i class="el-icon-upload el-icon--right"></i
      ></el-button>
      <div>
        <span>选择发布者：</span>
        <el-select
          v-model="articleForm.authorId"
          clearable
          :disabled="$route.params.id?true:false"
          placeholder="请选择发布者"
        >
          <el-option
            v-for="item in authorOptions"
            :key="item.value"
            :label="item.account"
            :value="item.id"
          >
          <span style="float: left">{{ item.account }}</span>
      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.nickname }}</span>
          </el-option>
        </el-select>
      </div>
    </div>
    <el-container>
      <el-container class="me-area me-write-box">
        <el-main class="me-write-main">
          <div class="me-write-title">
            <el-input
              resize="none"
              type="textarea"
              autosize
              v-model="articleForm.title"
              placeholder="请输入标题"
              class="me-write-input"
              :disabled="!this.articleForm.editor.toolbarsFlag"
            >
            </el-input>
          </div>
          <div
            id="placeholder"
            style="visibility: hidden; height: 89px; display: none"
          ></div>
          <markdown-editor
            :editor="articleForm.editor"
            class="me-write-editor"
          ></markdown-editor>
        </el-main>
      </el-container>

      <el-dialog
        title="摘要 分类 标签"
        :visible.sync="publishVisible"
        :close-on-click-modal="false"
        custom-class="me-dialog"
        append-to-body
      >
        <el-form :model="articleForm" ref="articleForm" :rules="rules">
          <el-form-item prop="summary">
            <el-input
              type="textarea"
              v-model="articleForm.summary"
              :rows="6"
              placeholder="请输入摘要"
            >
            </el-input>
          </el-form-item>

          <el-form-item label="文章分类" prop="category">
            <el-select
              v-model="articleForm.category"
              value-key="id"
              placeholder="请选择文章分类"
            >
              <el-option
                v-for="c in categorys"
                :key="c.id"
                :label="c.categoryName"
                :value="c"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="文章标签" prop="tags">
            <el-checkbox-group v-model="articleForm.tags">
              <el-checkbox
                v-for="t in tags"
                :key="t.id"
                :label="t.id"
                name="tags"
                >{{ t.tagName }}</el-checkbox
              >
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="publishVisible = false">取 消</el-button>
          <el-button type="primary" @click="publish('articleForm')"
            >发布</el-button
          >
        </div>
      </el-dialog>
    </el-container>
  </div>
</template>

<script>
import MarkdownEditor from "@/components/table/MarkdownEditor";
import { addArticle, updateArticle } from "@/api/article";
import { selectUser } from "@/api/user";
import { selectCategory } from "@/api/category";
import { selectTag } from "@/api/tag";

export default {
  name: "ArticlePublish",
  mounted() {
    console.log(this);
    this.getAuthorOptions();
    this.getCategorysAndTags();
    if (this.$route.params.id) {
      this.edit();
    }
    // this.editorToolBarToFixedWrapper = this.$_.throttle(
    //   this.editorToolBarToFixed,
    //   200
    // );
    window.addEventListener("scroll", this.editorToolBarToFixedWrapper, false);
  },
  beforeDestroy() {
    this.$store.commit("SET_MARK", null); //清除vuex里的数据
    this.$store.commit("SET_DEFAULTOPEN", null);
    window.removeEventListener(
      "scroll",
      this.editorToolBarToFixedWrapper,
      false
    );
  },
  data() {
    return {
      page: {
        current: 1,
        pageSize: 1000,
      },
      publishVisible: false,
      categorys: [],
      tags: [],
      authorOptions: [],
      articleForm: {
        id: "",
        title: "",
        summary: "",
        category: "",
        authorId: "",
        tags: [],
        preimg: "", //预览图
        editor: {
          value: "",
          ref: "", //保存mavonEditor实例  实际不该这样
          defaultOpen: "edit",
          toolbarsFlag: true, //工具栏是否开启
          subfield: true, //单双栏模式
          toolbars: {
            bold: true, // 粗体
            italic: true, // 斜体
            header: true, // 标题
            underline: true, // 下划线
            strikethrough: true, // 中划线
            mark: true, // 标记
            superscript: true, // 上角标
            subscript: true, // 下角标
            quote: true, // 引用
            ol: true, // 有序列表
            ul: true, // 无序列表
            link: true, // 链接
            imagelink: true, // 图片链接
            code: true, // code
            fullscreen: true, // 全屏编辑
            readmodel: true, // 沉浸式阅读
            help: true, // 帮助
            undo: true, // 上一步
            redo: true, // 下一步
            trash: true, // 清空
            navigation: true, // 导航目录
            subfield: true, // 单双栏模式
            preview: true, // 预览
          },
        },
      },
      rules: {
        summary: [
          { required: true, message: "请输入摘要", trigger: "blur" },
          { max: 80, message: "不能大于80个字符", trigger: "blur" },
        ],
        category: [
          { required: true, message: "请选择文章分类", trigger: "change" },
        ],
        tags: [
          {
            type: "array",
            required: true,
            message: "请选择标签",
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {
    title() {
      return "写文章 - news-back";
    },
  },
  watch: {
    "$store.state.defaultopen": {
      handler(newName, oldName) {
        if (newName == "preview") {
          this.articleForm.editor.defaultOpen = newName;
          this.articleForm.editor.toolbarsFlag = false;
          this.articleForm.editor.subfield = false;
        }
      },
      immediate: true,
    },
  },
  methods: {
    edit() {
      this.articleForm.title = this.$store.state.mark.title;
      this.articleForm.id = this.$store.state.mark.id;
      this.articleForm.summary = this.$store.state.mark.summary;
      this.articleForm.authorId=this.$store.state.mark.authorId
      this.articleForm.category = this.$store.state.mark.categoryId;
      this.articleForm.tags = this.$store.state.mark.tags.map(function (item) {
        return item.id;
      });
      this.articleForm.editor.value = this.$store.state.mark.content;
    },
    formatter() {
      // let str = this.articleForm.editor.value;
      // if (str.match(/!\[(.*?)\]\((.*?)\)/)) {
      //   let result = str.match(/!\[(.*?)\]\((.*?)\)/); //将写入的内容将第一张图片匹配出来
      //   this.articleForm.preimg = result[2];
      // }
      this.articleForm.preimg = "";
      let str = this.articleForm.editor.value;
      let pattern = /!\[(.*?)\]\((.*?)\)/gm;
      let matcher;
      while ((matcher = pattern.exec(str)) !== null) {
        if (this.articleForm.preimg) {
          this.articleForm.preimg += "," + matcher[2];
        } else {
          this.articleForm.preimg = matcher[2];
        }
      }
    },
    getAuthorOptions() {
      selectUser({
        page: 1,
        pageSize: 100000,
      })
        .then((res) => {
          this.authorOptions=res.data.records.filter(element=>{
            return element.admin==1
          })
        })
        .catch((err) => {
          console.log(err);
        });
    },
    publishShow() {
      this.formatter();
      if (!this.articleForm.title) {
        this.$message({
          message: "标题不能为空哦",
          type: "warning",
          showClose: true,
        });
        return;
      }

      if (this.articleForm.title.length > 30) {
        this.$message({
          message: "标题不能大于30个字符",
          type: "warning",
          showClose: true,
        });
        return;
      }

      if (!this.articleForm.editor.ref.d_render) {
        this.$message({
          message: "内容不能为空哦",
          type: "warning",
          showClose: true,
        });
        return;
      }

      if(this.articleForm.authorId===''){
        this.$message({
          message: "发布者不能为空哦",
          type: "warning",
          showClose: true,
        });
        return;
      }
      this.publishVisible = true;
    },
    publish(articleForm) {
      this.$refs[articleForm].validate((valid) => {
        if (valid) {
          let tags = this.articleForm.tags.map(function (item) {
            return { id: item };
          });

          let article = {
            id: this.articleForm.id,
            title: this.articleForm.title,
            summary: this.articleForm.summary,
            category: this.articleForm.category,
            authorId:this.articleForm.authorId,
            tags: tags,
            preimg: this.articleForm.preimg,
            body: {
              content: this.articleForm.editor.value,
              contentHtml: this.articleForm.editor.ref.d_render,
            },
          };

          let article1 = {
            id: this.articleForm.id,
            title: this.articleForm.title,
            summary: this.articleForm.summary,
            category: this.articleForm.category,
            tags: tags,
            authorId:this.articleForm.authorId,
            preimg: this.articleForm.preimg,
            body: {
              content: this.articleForm.editor.value,
              contentHtml: this.articleForm.editor.ref.d_render,
            },
          };

          this.publishVisible = false;

          let loading = this.$loading({
            lock: true,
            text: "发布中，请稍后...",
          });
          if (this.$route.params.id) {
            updateArticle(article1)
              .then((data) => {
                console.log(data);
                if (data.success) {
                  loading.close();
                  this.$message({
                    message: "发布成功啦",
                    type: "success",
                    showClose: true,
                  });
                  this.$router.push({ path: "/article" });
                } else {
                  this.$message({
                    message: "发布文章失败:" + data.msg,
                    type: "error",
                    showClose: true,
                  });
                }
              })
              .catch((error) => {
                loading.close();
                if (error !== "error") {
                  this.$message({
                    message: error,
                    type: "error",
                    showClose: true,
                  });
                }
              });
          } else {
            addArticle(article)
              .then((data) => {
                console.log(data);
                if (data.success) {
                  loading.close();
                  this.$message({
                    message: "发布成功啦",
                    type: "success",
                    showClose: true,
                  });
                  this.$router.push({ path: "/article" });
                } else {
                  this.$message({
                    message: "发布文章失败:" + data.msg,
                    type: "error",
                    showClose: true,
                  });
                }
              })
              .catch((error) => {
                loading.close();
                if (error !== "error") {
                  this.$message({
                    message: error,
                    type: "error",
                    showClose: true,
                  });
                }
              });
          }
        } else {
          return false;
        }
      });
    },
    getCategorysAndTags() {
      selectCategory(this.page)
        .then((data) => {
          if (data.success) {
            this.categorys = data.data.records;
          } else {
            this.$message({
              type: "error",
              message: "文章分类加载失败",
              showClose: true,
            });
          }
        })
        .catch((error) => {
          if (error !== "error") {
            this.$message({
              type: "error",
              message: "文章分类加载失败",
              showClose: true,
            });
          }
        });

      selectTag(this.page)
        .then((data) => {
          if (data.success) {
            this.tags = data.data.records;
          } else {
            this.$message({
              type: "error",
              message: "标签加载失败",
              showClose: true,
            });
          }
        })
        .catch((error) => {
          if (error !== "error") {
            this.$message({
              type: "error",
              message: "标签加载失败",
              showClose: true,
            });
          }
        });
    },
    editorToolBarToFixed() {
      let toolbar = document.querySelector(".v-note-op");
      let curHeight =
        document.documentElement.scrollTop || document.body.scrollTop;
      if (curHeight >= 160) {
        document.getElementById("placeholder").style.display = "block"; //bad  用计算属性较好
        toolbar.classList.add("me-write-toolbar-fixed");
      } else {
        document.getElementById("placeholder").style.display = "none";
        toolbar.classList.remove("me-write-toolbar-fixed");
      }
    },
  },
  components: {
    "markdown-editor": MarkdownEditor,
  },
  //组件内的守卫 调整body的背景色
  beforeRouteEnter(to, from, next) {
    window.document.body.style.backgroundColor = "#fff";
    next();
  },
  beforeRouteLeave(to, from, next) {
    window.document.body.style.backgroundColor = "#f5f5f5";
    next();
  },
};
</script>

<style>
.publish {
  display: flex;
  justify-content: space-between;
}
.me-write-info {
  line-height: 60px;
  font-size: 18px;
  font-weight: 600;
}

.me-write-btn {
  margin-top: 10px;
}

.me-write-box {
  margin: 40px auto 0;
}

.me-write-main {
  padding: 0;
}

.me-write-input textarea {
  font-size: 32px;
  font-weight: 600;
  height: 20px;
  border: none;
}

.me-write-editor {
  min-height: 650px !important;
}

.me-title img {
  max-height: 2.4rem;
  max-width: 100%;
}

.me-write-toolbar-fixed {
  position: fixed;
  width: 700px !important;
  top: 60px;
}

.v-note-op {
  box-shadow: none !important;
}

.auto-textarea-block {
  font-size: 18px !important;
}
</style>
